package net.mikoo.seals.api.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;

import net.mikoo.seals.api.model.BaseResponse;
import net.mikoo.seals.api.model.ResultType;
import net.mikoo.seals.api.utility.ApiConstants;
import net.mikoo.seals.api.utility.PartyUtility;
import net.mikoo.seals.model.Party;

public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
	
	@Autowired
	private RedisTemplate<String, Object> objectRedisTemplate;
	
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String token = request.getHeader("token");
		if(StringUtils.isBlank(token)) {
			token = request.getParameter("token");
			if(StringUtils.isBlank(token)) {
				needLoginResponse(response);
				return false;
			}
		}
		Object partyObj = objectRedisTemplate.opsForValue().get(ApiConstants.MPI_OAUTH_TOKEN_TAG + token);
		if(partyObj == null) {
			needLoginResponse(response);
			return false;
		}
		request.setAttribute("party", (Party)partyObj);
		return true;
	}

	private void needLoginResponse(HttpServletResponse response) {
		assert response != null;
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        
        BaseResponse res = new BaseResponse();
        res.setResult(ResultType.NEED_LOGIN.getValue());
        res.setErrorMsg("need login");
		
		PrintWriter writer = null;
		try {
			String json = JSONObject.toJSONString(res);
			writer = response.getWriter();
            writer.print(json);
            writer.flush();
		}catch(Exception e) {
			logger.error("", e);
		}finally {
			if(writer != null) {
				writer.close();
			}
		}
	}
}
